const queryTagGoods = async (index) => {
	try {
		const goodsList = await getAllGoods(index);
		renderGoods(goodsList, doms.tagGoodsContainer);
	} catch (error) {
		console.error('商品加载失败:', error);
		doms.tagGoodsContainer.innerHTML = '<div class="error">商品加载失败</div>';
	}
};

const renderGoods = (goodsList, container) => {
	if (!goodsList?.length) {
		container.innerHTML = '<div class="empty">暂无商品</div>';
		return;
	}

	const fragment = document.createDocumentFragment();

	goodsList.forEach(item => {
		const goodsItem = createGoodsItem(item);
		fragment.appendChild(goodsItem);
	});

	container.innerHTML = '';
	container.appendChild(fragment);
};

const createGoodsItem = ({
	storeId,
	primaryImage,
	title,
	spuTagList = [],
	minSalePrice,
	maxLinePrice
}) => {
	const item = document.createElement('div');
	item.className = 'goods_item';
	item.dataset.id = storeId;

	item.innerHTML = `
    <img src="${safeUrl(primaryImage)}" alt="${escapeHtml(title)}" class="goods_item_img" loading="lazy">
    <div class="goods_content">
      <h3 class="title">${escapeHtml(title)}</h3>
      <div class="goods_tag">${renderTags(spuTagList)}</div>
      <div class="goods_item_option">
        <div class="price">
          <span class="current">¥${formatPrice(minSalePrice)}</span>
          ${maxLinePrice > minSalePrice 
            ? `<span class="original">¥${formatPrice(maxLinePrice)}</span>` 
            : ''}
        </div>
        <button class="add-cart" aria-label="加入购物车">
          <img src="img/ic_add_card.png" alt="加入购物车">
        </button>
      </div>
    </div>
  `;

	item.addEventListener('click', () => onGetGoodsItem(storeId));
	item.querySelector('.add-cart').addEventListener('click', e => {
		e.stopPropagation();
		onAddCard(storeId);
	});

	return item;
};

const renderTags = tags =>
	tags.map(tag => `<span class="tag">${escapeHtml(tag.title)}</span>`).join('');

// 工具函数
const safeUrl = url => url ? escapeHtml(url) : 'img/placeholder.jpg';
const formatPrice = price => Number(price).toFixed(2);
